<template>
  <div class="banner-container">
    <el-carousel :height="height" :interval="5000" arrow="hover">
      <el-carousel-item v-for="banner in banners" :key="banner.id">
        <router-link :to="banner.link">
          <img
            :src="banner.url"
            :alt="banner.title"
            class="w-full h-full object-cover"
          >
          <div class="banner-title">
            {{ banner.title }}
          </div>
        </router-link>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script setup>
import { ref, onMounted,onUnmounted } from 'vue'
import { getBanners } from '@/api/banners'

const banners = ref([])
const height = ref('400px')

// 获取轮播图数据
const fetchBanners = async () => {
  try {
    const res = await getBanners()
    banners.value = res.data
  } catch (error) {
    console.error('获取轮播图失败:', error)
  }
}

onMounted(() => {
  fetchBanners()

  // 响应式调整轮播图高度
  const handleResize = () => {
    if (window.innerWidth < 640) {
      height.value = '200px'
    } else if (window.innerWidth < 1024) {
      height.value = '300px'
    } else {
      height.value = '400px'
    }
  }

  handleResize()
  window.addEventListener('resize', handleResize)

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
  })
})
</script>

<style scoped>
.banner-container {
  width: 100%;
  margin-bottom: 2rem;
}

.banner-title {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 1rem;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
  font-size: 1.25rem;
  font-weight: bold;
}

/* 移动端优化 */
@media (max-width: 640px) {
  .banner-title {
    font-size: 1rem;
    padding: 0.5rem;
  }
}

:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.3);
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.5);
}

:deep(.el-carousel__indicators) {
  bottom: 1rem;
}

:deep(.el-carousel__button) {
  width: 30px;
  border-radius: 4px;
}
</style>
